package com.google.appengine.a4ieve.servlets.resources;

import com.google.appengine.a4ieve.Helper;
import com.google.appengine.a4ieve.entities.AchievementWrapper;
import com.google.appengine.a4ieve.entities.StudentWrapper;
import com.google.appengine.api.datastore.*;
import com.google.appengine.api.users.UserServiceFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

class AchievementSavingServant implements Servant {

    private static final Logger LOG = Logger.getLogger(AchievementSavingServant.class.getName());
    private static final String FILE_NAME = "image";
    private static final String ACHIE_NAME = "fakeName";
    private static final String STATUS = "status";
    private static final String ID = "studentId";
    private static final String IS_POSITIVE = "isPositive";
    private static final String IMAGE_SOURCE = "imageSrc";
    private static final String REPLACE = "replace";
    private static final String EMAIL_SPLITTER = "\\@";

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp) {
        try {
            DatastoreService service = DatastoreServiceFactory.getDatastoreService();
            String replaceKey = req.getParameter(REPLACE);
            String userId = req.getParameter(ID);
            List<String> studIds = Arrays.asList(userId.split(EMAIL_SPLITTER));
            String achievement = req.getParameter(ACHIE_NAME);
            LOG.severe("Got achievement with name " + achievement + " with request content type " + req.getContentType() + " Try decoding " + URLEncoder.encode(achievement, "UTF-8"));
            String status = req.getParameter(STATUS);
            byte[] blobData = req.getParameter(FILE_NAME).getBytes();
            String saver = Helper.cropEmailId(UserServiceFactory.getUserService().getCurrentUser().getEmail());
            Integer isPositive = req.getParameter(IS_POSITIVE) == null ? 0 : Integer.parseInt(req.getParameter(IS_POSITIVE));
            String source = req.getParameter(IMAGE_SOURCE);
            Query studentQuery = new Query(StudentWrapper.KIND_KEY).addFilter(
                    StudentWrapper.USER_ID_PROPERTY,
                    Query.FilterOperator.IN,
                    studIds
            );
            Entity output = service.prepare(studentQuery).asList(FetchOptions.Builder.withLimit(1)).get(0);
            String groupId;

            groupId = (String) service.get(output.getKey()).getProperty(StudentWrapper.GROUP_KEY_PROPERTY);
            if (replaceKey != null) {
                Entity replaced = service.get(KeyFactory.stringToKey(replaceKey));
                String studId = studIds.get(0); //there will only be one - we ensured it on the client
                AchievementWrapper aObject = new AchievementWrapper.AchievementBuilder().googleId(studId).
                        status(status).name(achievement).blob(blobData).proposedBy(saver).isPositive(isPositive).
                        groupId(groupId).pictureUrl(source).build();
                replaced.setPropertiesFrom(aObject.getEntity());
                service.put(replaced);
            } else {
                for (String studId : studIds) {
                    AchievementWrapper aObject = new AchievementWrapper.AchievementBuilder().googleId(studId).
                            status(status).name(achievement).blob(blobData).proposedBy(saver).isPositive(isPositive).
                            groupId(groupId).pictureUrl(source).build();
                    Entity curator = aObject.getEntity();
                    service.put(curator);
                }
            }
        } catch (EntityNotFoundException e) {
            LOG.severe("Entity with not found by key");
        } catch (UnsupportedEncodingException ex) {
            LOG.severe("Unsupported encoding given");
        }
    }
}
